﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Genuilder.Extensibility
{
	public delegate void CodeDependencyHandler(CodeDependency sender, CodeItem target);
	public class CodeDependency
	{
		public CodeDependency(CodeItem source, CodeItem target)
		{
			if(source == null)
				throw new ArgumentNullException("source");
			if(target == null)
				throw new ArgumentNullException("target");
			_Source = source;
			_Target = target;

			_Source.StateChanged += new StateChangedHandler(_Source_StateChanged);
			_Source.ContentChanged += new ContentChangedHandler(_Source_ContentChanged);
			_Target.StateChanged += new StateChangedHandler(_Target_StateChanged);
		}

		void _Target_StateChanged(CodeItem sender, CodeItemState newState, CodeItemState oldState)
		{
			if(newState == CodeItemState.Deleted || newState == CodeItemState.Excluded)
				OnShouldUpdate();
		}


		public event CodeDependencyHandler ShouldUpdateTarget;

		void _Source_ContentChanged(CodeItem sender)
		{
			OnShouldUpdate();
		}

		bool _Updating;
		private void OnShouldUpdate()
		{
			if(ShouldUpdateTarget != null)
				ShouldUpdateTarget(this, Target);
		}

		void _Source_StateChanged(CodeItem sender, CodeItemState newState, CodeItemState oldState)
		{
			if(newState == CodeItemState.Deleted)
				Target.Delete();
			if(newState == CodeItemState.Excluded)
				Target.Exclude();
		}
		private readonly CodeItem _Source;
		public CodeItem Source
		{
			get
			{
				return _Source;
			}
		}

		private readonly CodeItem _Target;
		public CodeItem Target
		{
			get
			{
				return _Target;
			}
		}
	}
}
